//
//  FLLMakeFoodViewController.m
//  FLLGodOfCooking
//
//  Created by LL.F on 16/9/13.
//  Copyright © 2016年 LL.F. All rights reserved.
//

#import "FLLMakeFoodViewController.h"
#import "FLLMacro.h"
#import "FLLMethodModel.h"
#import "MethodData.h"
#import "MethodStep.h"
#import "MethodTags_Info.h"
#import "FLLMakeFoodTableViewcell.h"
#import "UIView+Frame.h"
#import "FLLMethodViewController.h"
#import "FLLFoodMaterialViewController.h"
#import "FLLRelatedViewController.h"
#import "FLLGoodAndBadViewController.h"
#import "FLLScrollTableViewCell.h"
#import "SelfSizeTool.h"

@interface FLLMakeFoodViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) FLLMethodModel *fllmethodModel;
@property (nonatomic, strong) MethodData *topCellData;
@property (nonatomic, strong) NSMutableArray<MethodTags_Info *> *collectionArray;
@property (nonatomic, strong) NSArray *sectionArray;
@property (nonatomic, strong) UIView *sectionHeaderView;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UIViewController *currentController;
@property (nonatomic, strong) UIButton *selectedButton;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) FLLScrollTableViewCell *cell;
@property (nonatomic, strong) UIView *navigationView;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *navigationLabel;
@property (nonatomic, strong) NSString *finalString;
@property (nonatomic, strong) UILabel *lineLabel;
@property (nonatomic, strong) NSString *bodyString;
/* "做法"数组 */
@property (nonatomic, strong) NSMutableArray<MethodStep *> *stepArray;
@end

@implementation FLLMakeFoodViewController
// 导航栏隐藏
- (void)viewWillAppear:(BOOL)animated
{

    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}
// 导航栏出现
- (void)viewWillDisappear:(BOOL)animated
{

    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self createPOSTRequest];
    [self createChildViewController];
    [self createFoodTableView];
    // 自定义view充当导航栏
    [self creatHeaderView];
    [self createScrollView];
    
   
    
}
// 自定义view充当导航栏
- (void)creatHeaderView {
    self.navigationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    [self.view addSubview:_navigationView];

    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backButton.frame = CGRectMake(20, 22, 40, 40);
    [self.backButton setImage:[UIImage imageNamed:@"nav_back_white"] forState:UIControlStateNormal];
    [_navigationView addSubview:_backButton];
    [_backButton addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)back:(UIButton *)btn {
    [self.navigationController popViewControllerAnimated:YES];
}
// 网络请求后才创建
- (void)creatNavigationLabel {
    self.navigationLabel = [[UILabel alloc] init];
    
    self.navigationLabel.textAlignment = 1;
    // 导航栏标题赋值
    self.navigationLabel.text = self.topCellData.dashes_name;
    [self.navigationView addSubview:_navigationLabel];
    [self.navigationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(_backButton.mas_centerY);
        make.centerX.mas_equalTo(0);
    }];
    self.navigationLabel.backgroundColor = [UIColor clearColor];
    self.navigationLabel.textColor = [UIColor clearColor];
    
    self.lineLabel = [[UILabel alloc] init];
    [_navigationView addSubview:_lineLabel];
    _lineLabel.backgroundColor = [UIColor clearColor];
    [_lineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.height.mas_equalTo(1);
    }];
}

- (void)createPOSTRequest
{
    
       if (![_idString containsString:@"#"]) {
        self.bodyString = [NSString stringWithFormat:@"methodName=DishesView&dishes_id=%@&version=4.40&", _idString];
    } else {
    self.finalString = [self.idString componentsSeparatedByString:@"#"][1];
    self.bodyString = [NSString stringWithFormat:@"methodName=DishesView&dishes_id=%@&version=4.40&", _finalString];
    }
    [ZWYNetTool POST:@"http://api.izhangchu.com/ HTTP/1.1" andBody:_bodyString andBodyStyle:ZWYBodyString andHeader:@{@"Content-Type":@"application/x-www-form-urlencoded; charset=utf-8"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
        
        self.fllmethodModel = [FLLMethodModel modelWithDic:result];
        self.topCellData = self.fllmethodModel.data;
        self.collectionArray = (NSMutableArray *)self.fllmethodModel.data.tags_info;
        self.stepArray = (NSMutableArray *)self.fllmethodModel.data.step;
        self.arrayBlock();
        [self creatNavigationLabel];
        [self.foodTableView reloadData];
        
    } andFailureBlock:^(NSError *error) {
        
    }];

    
}
- (void)createFoodTableView
{

    self.foodTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.foodTableView.delegate = self;
    self.foodTableView.dataSource = self;
    self.foodTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.foodTableView registerNib:[UINib nibWithNibName:@"FLLMakeFoodTableViewcell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"makeFoodTabelCell"];
    [self.foodTableView registerClass:[FLLScrollTableViewCell class] forCellReuseIdentifier:@"scrollTableCell"];
     
   
    [self.view addSubview:_foodTableView];
    
}
- (void)createChildViewController
{

     FLLMethodViewController *methodVC = [[FLLMethodViewController alloc] init];
    
    __weak FLLMakeFoodViewController *weakSelf = self;
    self.moveBlock = ^(BOOL able){

        methodVC.methodTableView.scrollEnabled = able;
    };
    self.arrayBlock = ^(){
    methodVC.stepArray = weakSelf.stepArray;
    };
     [self addChildViewController:methodVC];
     FLLFoodMaterialViewController *foodMaterialVC = [[FLLFoodMaterialViewController alloc] init];
    if (![_idString containsString:@"#"]) {
        foodMaterialVC.idString = self.idString;
    } else {
        foodMaterialVC.idString = _finalString;
    }
     [self addChildViewController:foodMaterialVC];
     FLLRelatedViewController *relatedVC = [[FLLRelatedViewController alloc] init];
    if (![_idString containsString:@"#"]) {
        relatedVC.idString = self.idString;
    } else {
        relatedVC.idString = _finalString;
    }
     [self addChildViewController:relatedVC];
     FLLGoodAndBadViewController *goodAndBadVC = [[FLLGoodAndBadViewController alloc] init];
    if (![_idString containsString:@"#"]) {
        goodAndBadVC.idString = self.idString;
    } else {
        goodAndBadVC.idString = _finalString;
    }
     [self addChildViewController:goodAndBadVC];

    
}
- (void)createScrollView
{

    self.scrollView = [[UIScrollView alloc] init];
    _scrollView.contentSize = CGSizeMake(self.childViewControllers.count * SCREEN_WIDTH, 0);
    _scrollView.fll_width = SCREEN_WIDTH;
    _scrollView.fll_height = 550 * kHeightScale;
    _scrollView.delegate = self;
    _scrollView.pagingEnabled = YES;
    
    [self.cell.contentView insertSubview:_scrollView atIndex:0];
    [self scrollViewDidEndScrollingAnimation:_scrollView];

    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0) {
    FLLMakeFoodTableViewcell *cell = [tableView dequeueReusableCellWithIdentifier:@"makeFoodTabelCell"];
    
        [cell.dishImageView sd_setImageWithURL:[NSURL URLWithString:_topCellData.image] placeholderImage:[UIImage new] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
        }];
        
        cell.prepareLabel.font = [UIFont systemFontOfSize:14 * kWidthScale];
        cell.makeLabel.font = [UIFont systemFontOfSize:14 * kWidthScale];
        cell.downloadLabel.font = [UIFont systemFontOfSize:14 * kWidthScale];
        
        cell.dishNameLabel.text = _topCellData.dashes_name;
        cell.dishNameLabel.font = [UIFont systemFontOfSize:15 * kWidthScale];
        cell.contentLabel.text = _topCellData.material_desc;
        cell.contentLabel.font = [UIFont systemFontOfSize:13 * kWidthScale];
        cell.timeLabel.text = [NSString stringWithFormat:@"时长:%@", _topCellData.cooke_time];
        cell.timeLabel.font = [UIFont systemFontOfSize:12 * kWidthScale];
        cell.hardLabel.text = [NSString stringWithFormat:@"难易程度:%@", _topCellData.hard_level];
        cell.hardLabel.font = [UIFont systemFontOfSize:12 * kWidthScale];
        cell.tastyLabel.text = [NSString stringWithFormat:@"口味:%@", _topCellData.taste];
        cell.tastyLabel.font = [UIFont systemFontOfSize:12 * kWidthScale];
        cell.collectionArray = self.collectionArray;
    return cell;
    
    }
    
    self.cell = [tableView dequeueReusableCellWithIdentifier:@"scrollTableCell"] ;
    self.cell.scrollView.delegate = self;
    self.cell.scrollView.contentSize = CGSizeMake(self.childViewControllers.count * SCREEN_WIDTH, 0);
    self.scrollView = self.cell.scrollView;
    self.cell.scrollView.pagingEnabled = YES;
    [self scrollViewDidEndScrollingAnimation:self.cell.scrollView];

    return _cell;
    
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.section == 0) {
        return SCREEN_WIDTH * 50 / 30.0f;
    }
    return 580 * kHeightScale;
}
// 分区头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        self.sectionArray = [NSArray arrayWithObjects:@"做法", @"食材", @"相关常识", @"相宜相克", nil];
        self.sectionHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50 * kHeightScale)];
        self.sectionHeaderView.backgroundColor = [UIColor whiteColor];
        self.lineView = [[UIView alloc] init];
        self.lineView.fll_height = 3;
        self.lineView.backgroundColor = FLLOrangeColor;
        for (int i = 0; i < self.sectionArray.count; i++) {
            UIButton *titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
            titleButton.frame = CGRectMake(CGRectGetWidth(_sectionHeaderView.bounds) / _sectionArray.count / 1.0 * i, 0, CGRectGetWidth(_sectionHeaderView.bounds) / _sectionArray.count / 1.0 , CGRectGetHeight(_sectionHeaderView.bounds) - 3);
            
            titleButton.titleLabel.font = [UIFont systemFontOfSize:16 * kWidthScale];
            [titleButton setTitle:_sectionArray[i] forState:UIControlStateNormal];
            [titleButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            [titleButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateDisabled];
            titleButton.tag = 1000 + i;
            [titleButton addTarget:self action:@selector(didClickedTitleButton:) forControlEvents:UIControlEventTouchUpInside];
            [self.sectionHeaderView addSubview:titleButton];
            self.lineView.fll_y = titleButton.frame.size.height;
            if (i == 0) {
        
                [self didClickedTitleButton:titleButton];
                self.lineView.fll_width = titleButton.titleLabel.fll_width;
                self.lineView.fll_centerX = titleButton.center.x;
                
            }
        }
    
        [self.sectionHeaderView addSubview:_lineView];
        return _sectionHeaderView;
    }
    return nil;
   
    
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    if (scrollView == self.scrollView) {
        NSInteger i = scrollView.contentOffset.x / SCREEN_WIDTH ;
        self.currentController = self.childViewControllers[i];
        self.currentController.view.frame = CGRectMake(scrollView.contentOffset.x, 0, SCREEN_WIDTH, 550* kHeightScale);
        [scrollView addSubview:_currentController.view];

    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.scrollView) {
        [self scrollViewDidEndScrollingAnimation:scrollView];
        NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH;
        [self didClickedTitleButton:self.sectionHeaderView.subviews[index]];
    
    }
}

- (void)didClickedTitleButton:(UIButton *)button
{

    self.selectedButton.enabled = YES;
    button.enabled = NO;
    NSInteger i = button.tag - 1000;
    [UIView animateWithDuration:0.2 animations:^{
        self.lineView.fll_width = button.fll_width;
        self.lineView.fll_centerX = button.fll_centerX;
    }];
    self.selectedButton = button;
    [self.scrollView addSubview:_currentController.view];
    CGFloat index = i * SCREEN_WIDTH;
    [self.scrollView setContentOffset:CGPointMake(index, 0) animated:YES];

    
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }

    return 50 * kHeightScale;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.foodTableView) {
      
        
        CGFloat offset_y = scrollView.contentOffset.y;
        CGFloat alpha = (offset_y + 20 - 400) * kHeightScale / 200.0f;
        if (scrollView.contentOffset.y <= 50 * kHeightScale && scrollView.contentOffset.y >= 0) {
            scrollView.contentInset = UIEdgeInsetsMake(- scrollView.contentOffset.y , 0, 0, 0);
        }else if (scrollView.contentOffset.y > 50 * kHeightScale) {
            scrollView.contentInset = UIEdgeInsetsMake(64 * kHeightScale, 0, 0, 0);
        }
        self.navigationView.backgroundColor = [UIColor colorWithWhite:1.000 alpha:alpha];
        self.navigationLabel.textColor = [UIColor colorWithWhite:0.108 alpha:alpha];
        if (offset_y < 587) {
            [self.backButton setImage:[UIImage imageNamed:@"nav_back_white"] forState:UIControlStateNormal];
            self.lineLabel.backgroundColor = [UIColor clearColor];
            self.moveBlock(NO);
        }
        if (offset_y >= 587) {
            
            [self.backButton setImage:[UIImage imageNamed:@"nav_back_black"] forState:UIControlStateNormal];
            self.lineLabel.backgroundColor = [UIColor lightGrayColor];
            self.moveBlock(YES);
        }
       
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
